package org.learn.dormi330;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * SimpleDateFormat非线程安全
 * why: https://stackoverflow.com/questions/6840803/why-is-javas-simpledateformat-not-thread-safe
 * 这个类里面有状态 SimpleDateFormat stores intermediate results in instance fields.
 * <p>
 * 这里演示以下 thread unsafe
 *
 * @author : dormi330
 * @since : 22/02/06
 */
public class SimpleDateFormatNotThreadSafe {
    private static SimpleDateFormat simpleDateFormat =
        new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static void main(String[] args) {
        String dateStr = "2018-06-22 10:00:00";

        ExecutorService executorService = Executors.newFixedThreadPool(10);
        Runnable task = new Runnable() {
            @Override
            public void run() {
                parseDate(dateStr);
            }
        };

        for (int i = 0; i < 100; i++) {
            executorService.submit(task);
        }
        executorService.shutdown();
    }

    private static void parseDate(String dateStr) {
        try {
            Date date = simpleDateFormat.parse(dateStr);
            System.out.println("Successfully Parsed Date " + date);
        } catch (ParseException e) {
            System.out.println("ParseError " + e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
